package cn.ybk.user.controller;

import cn.ybk.basic.util.AjaxResult;
import cn.ybk.basic.util.PageList;
import cn.ybk.user.dto.LoginFormDto;
import cn.ybk.user.service.IUserService;
import cn.ybk.user.domain.User;
import cn.ybk.user.query.UserQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    public IUserService userService;


    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody User user) {
        try {
            if (user.getId() != null)
                userService.update(user);
            else
                userService.add(user);
            return AjaxResult.me().success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().fail();
        }
    }


    @DeleteMapping(value = "/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            userService.delete(id);
            return AjaxResult.me().success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().fail();
        }
    }

    //获取用户
    @GetMapping("/{id}")
    public User get(@PathVariable("id") Long id) {
        return userService.findById(id);
    }


    @GetMapping()
    public List<User> list() {

        return userService.findAll();
    }

    @PostMapping("/list")
    public PageList<User> json(@RequestBody UserQuery query) {
        return userService.queryByPage(query);
    }

    @PostMapping("/account")
    public AjaxResult account(@RequestBody @Valid LoginFormDto dto) {
        return userService.account(dto);

    }



}
